package com.example.zk.client;

import org.apache.zookeeper.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by SOAL on 2017/7/9 0009.
 */
public class DisClient {
    public static final String connectString = "192.168.1.142:2181,192.168.1.140:2181,192.168.1.143:2181";
    public static final int sessionTimeout = 50000;
    public static final String parentNode = "/servers";

    private volatile List<String> serverList ;


    ZooKeeper zkClent = null;


    public void getConnect() throws Exception {
        zkClent = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                //收到事件通知后回调函数（自己事件处理逻辑）
                System.out.println(watchedEvent.getType() + "----" + watchedEvent.getPath());
                try {
                    getServerList();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public  void mybuss(String hostname) throws InterruptedException {
        System.out.println(hostname+" -- is running");
        Thread.sleep(   Long.MAX_VALUE);

    }

    public  void getServerList() throws Exception {
        List<String> children =zkClent.getChildren(parentNode,true);
        List<String> servers =  new ArrayList<String>();
        for (String child: children
             ) {
            byte[] data=zkClent.getData(parentNode+"/"+child,false ,null);
            servers.add(new String(data));
        }
        serverList=servers;
        System.out.println(serverList);


    }

    public static void main(String[] args) throws Exception {
        DisClient disSerer=new DisClient();
        disSerer.getConnect();

        String ssd="ddddr";
        disSerer.getServerList();
        disSerer.mybuss(ssd);


    }
}
